//
//  PlayerInfoViewController.m
//  NBAPro
//
//  Created by 李广松 on 16/6/29.
//  Copyright © 2016年 WYH. All rights reserved.
//

#import "PlayerInfoViewController.h"

@implementation PlayerInfoViewController {
    
    UITableView *lineTableView;
    
    NSString *playerId;
    
    NSArray *playerInfo;
    
    NSArray *playerAllGamesArr;
    
    NSArray *playerCurrentGameInfoArr;
    
    UILabel *DateLabel;
    
    NSString *gameDateStr;
    
    NSArray *dataNameArr;
    NSMutableDictionary *lineDataDic;
    
    int index;
    
}


- (id)initWithPlayerId:(NSString *)player {

    self = [super init];
    
    if (self) {
    
         playerId = player;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    dataNameArr = @[@"Points", @"Assists", @"Rebounds", @"Steals", @"Blocks", @"Turnovers", @"Minutes"];
    lineDataDic = [[NSMutableDictionary alloc] init];
    
    index = 0;
    
    [self getPlayerAllInfo];
    [self getPlayerAllGameInfo];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
}

- (UITableView *)createTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.userInteractionEnabled = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    return tableView;
    
}
#pragma mark - 球员信息获取
- (void)getPlayerAllInfo {
    
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@commonplayerinfo?PlayerID=%@",  API_BASE_URL_NBA,playerId];
    NSURL *url = [[NSURL alloc] initWithString: urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            [self performSelectorOnMainThread:@selector(getPlayerBasicInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
}


- (void)getPlayerBasicInfo:(NSDictionary *)result {
    
    playerInfo = result[@"resultSets"];
    
    UIColor *topColor = [GetInfo getTeamColorWithTeamName:playerInfo[0][@"rowSet"][0][17]];
    UIView *topView = [self createTopViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200) AndBackgroundColor:topColor AndPlayerName:playerInfo[0][@"rowSet"][0][3] AndPlayerNumber:playerInfo[0][@"rowSet"][0][13]];
    [self.view addSubview:topView];
    
    UIView *playerAverageDataView = [self createPlayerAverageDataWithFrame:CGRectMake(0, topView.frame.size.height, self.view.frame.size.width, 50)];
    [self.view addSubview:playerAverageDataView];
    
}



- (void)getPlayerAllGameInfo {
    
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@playergamelog?Season=2015-16&PlayerID=%@&SeasonType=Regular%%20Season", API_BASE_URL_NBA,playerId];
    NSURL *url = [[NSURL alloc] initWithString: urlStr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            [self performSelectorOnMainThread:@selector(getPlayerCurrentGameInfo:) withObject:result waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
}


- (void)getPlayerCurrentGameInfo:(NSDictionary *)result {
    
    playerAllGamesArr = result[@"resultSets"][0][@"rowSet"];
    
    lineTableView = [self createTableViewWithFrame:CGRectMake(0, 250, self.view.frame.size.width, 245)];
    [self.view addSubview:lineTableView];
    
    [self refreshPlayerChartView];
    
    UIView *gameDateView = [self createDateViewWithFrame:CGRectMake(0, 250 + 245, self.view.frame.size.width, 54)];
    [self.view addSubview:gameDateView];
    
    UIView *cutLineView = [[UIView alloc] initWithFrame:CGRectMake(12, gameDateView.frame.origin.y + gameDateView.frame.size.height, self.view.frame.size.width - 24, 3)];
    cutLineView.backgroundColor = [UIColor colorWithRed:234/255.0 green:234/255.0 blue:234/255.0 alpha:1];
    [self.view addSubview:cutLineView];
}


#pragma mark - 点击事件

- (void)touchNextDate {
    index--;
    [self refreshPlayerChartView];
    
}

- (void)touchLastDate {
    index++;
    
    [self refreshPlayerChartView];
}


- (void)touchReturn {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITalbeViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return dataNameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PlayerInfoLineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[PlayerInfoLineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSString *mark = dataNameArr[indexPath.row];
    
    cell.titleLabel.text = mark;
    if ( [lineDataDic[mark] floatValue] * 7 > 375) {
        cell.lineView.frame = CGRectMake(cell.lineView.frame.origin.x, cell.lineView.frame.origin.y, 375, cell.lineView.frame.size.height);
    }
    else {
        cell.lineView.frame = CGRectMake(cell.lineView.frame.origin.x, cell.lineView.frame.origin.y, [lineDataDic[mark] floatValue] * 7, cell.lineView.frame.size.height);
    }
    cell.lineView.backgroundColor = [self getCellLineColorWithIndex:indexPath.row];
    cell.dataLabel.text = [[NSString alloc] initWithFormat:@"%@", lineDataDic[mark]];
    cell.dataLabel.frame = CGRectMake(cell.lineView.frame.origin.x + cell.lineView.frame.size.width + 4, cell.dataLabel.frame.origin.y, 50, 12);
    
    return cell;
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 35;
}



#pragma mark - 界面
- (UIView *)createTopViewWithFrame:(CGRect)frame AndBackgroundColor:(UIColor *)color AndPlayerName:(NSString *)name AndPlayerNumber:(NSString *)number{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = color;
    
    UIView *returnIcon = [self createReturnIconWithFrame:CGRectMake(0, 20, 10.4 + 25 , 17.4 + 25)];
    [view addSubview:returnIcon];
    
    UILabel *nameLab = [CreateControl createLabelWithFrame:CGRectMake(0, view.frame.size.height - 50, self.view.frame.size.width, 20) AndText:name AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:19];
    [view addSubview:nameLab];
    
    UILabel *numberLab = [CreateControl createLabelWithFrame:CGRectMake(0, view.frame.size.height - 25, self.view.frame.size.width, 18) AndText:number AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:17];
    [view addSubview:numberLab];
    
    
    UIView *headView = [self createPlayerHeadViewWithFrame:CGRectMake(self.view.frame.size.width / 2 - 100 / 2, nameLab.frame.origin.y - 8 - 100, 100, 100)];
    [view addSubview:headView];
    
    return view;
    
}

- (UIView *)createReturnIconWithFrame:(CGRect)frame {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    UIImage *returnImg = [UIImage imageNamed:@"return"];
    UIImageView *returnImgView = [[UIImageView alloc] initWithFrame:CGRectMake(25, 0, returnImg.size.width, returnImg.size.height)];
    returnImgView.image = returnImg;
    [view addSubview:returnImgView];
    
    UIButton *returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, returnImgView.frame.origin.y, returnImg.size.width + 25, returnImg.size.height)];
    [returnBtn addTarget:self action:@selector(touchReturn) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:returnBtn];
    
    return view;
}

- (UIView *)createPlayerHeadViewWithFrame:(CGRect)frame {
    
    UIView *headView = [[UIView alloc] initWithFrame:frame];
    headView.backgroundColor = [UIColor whiteColor];
    headView.layer.cornerRadius = 50;
    headView.layer.masksToBounds = YES;
    
    UIImageView *headImgView = [[UIImageView alloc] initWithFrame:CGRectMake(headView.frame.size.width / 2 - 110 / 2, headView.frame.size.height / 2 - 65 / 2 - 1.8, 110, 86)];
    headImgView.image = [self getHeadImg];
    [headView addSubview:headImgView];
    
    return headView;
    
}

- (UIImage *)getHeadImg {
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@media/players/230x185/%@.png", API_BASE_URL_NBA_BASE ,playerId];
    NSURL *imgUrl = [[NSURL alloc] initWithString:urlStr];
    UIImage *headImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgUrl] ];
    
    return headImg;
}


- (UIView *)createPlayerAverageDataWithFrame:(CGRect)frame {
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor whiteColor];
    
    NSString *pointData;
    NSString *asistantData;
    NSString *reboundsData;
    
    NSArray *markArr = playerInfo[1][@"rowSet"];
    if (markArr.count == 0) {
        pointData = @"0.0";
        asistantData = @"0.0";
        reboundsData = @"0.0";
    }
    else {
        pointData = [self changeDecimalAccuracy:playerInfo[1][@"rowSet"][0][3]];
        asistantData = [self changeDecimalAccuracy:playerInfo[1][@"rowSet"][0][4]];
        reboundsData = [self changeDecimalAccuracy:playerInfo[1][@"rowSet"][0][5]];

    }
    
    UILabel *pointDataLab = [self createAverageLabWithPosition:CGPointMake(60, 16) AndText:pointData AndFont:18];
    UILabel *pointLab = [self createAverageLabWithPosition:CGPointMake(pointDataLab.frame.origin.x + pointDataLab.frame.size.width + 3, 15 + 6) AndText:@"Points" AndFont:12];
    [view addSubview:pointDataLab];
    [view addSubview:pointLab];
    
    
    UILabel *asistantDataLab = [self createAverageLabWithPosition:CGPointMake(pointLab.frame.origin.x + pointLab.frame.size.width + 35, 16) AndText:asistantData AndFont:18];
    UILabel *asistantLab = [self createAverageLabWithPosition:CGPointMake(asistantDataLab.frame.origin.x + asistantDataLab.frame.size.width + 3, pointLab.frame.origin.y) AndText:@"Asistant" AndFont:12];
    [view addSubview:asistantDataLab];
    [view addSubview:asistantLab];
    
    
    UILabel *reboundDataLab = [self createAverageLabWithPosition:CGPointMake(asistantLab.frame.origin.x + asistantLab.frame.size.width + 35, pointDataLab.frame.origin.y) AndText:reboundsData AndFont:18];
    UILabel *reboundLab = [self createAverageLabWithPosition:CGPointMake(reboundDataLab.frame.origin.x + reboundDataLab.frame.size.width + 3 , pointLab.frame.origin.y) AndText:@"Rebounds" AndFont:12];
    [view addSubview:reboundDataLab];
    [view addSubview:reboundLab];
    
    return view;
}

- (UILabel *)createAverageLabWithPosition:(CGPoint)point AndText:(NSString *)text AndFont:(float)font{
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font]}];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(point.x, point.y, size.width, font + 1)];
    label.text = text;
    label.font = [UIFont systemFontOfSize:font];
    label.textColor = [UIColor colorWithRed:126/255.0 green:138/255.0 blue:159/255.0 alpha:1];
    
    
    return label;
}


- (UIColor *)getCellLineColorWithIndex:(float)i {
    UIColor *color;
    switch ((int)i) {
        case 0:
            color = [UIColor colorWithRed:230/255.0 green:58/255.0 blue:51/255.0 alpha:1];
            break;
        case 1:
            color = [UIColor colorWithRed:245/255.0 green:176/255.0 blue:39/255.0 alpha:1];
            break;
        case 2:
            color = [UIColor colorWithRed:245/255.0 green:176/255.0 blue:39/255.0 alpha:1];
            break;
        case 3:
            color = [UIColor colorWithRed:62/255.0 green:131/255.0 blue:221/255.0 alpha:1];
            break;
        case 4:
            color = [UIColor colorWithRed:53/255.0 green:126/255.0 blue:63/255.0 alpha:1] ;
            break;
        case 5:
            color = [UIColor colorWithRed:104/255.0 green:102/255.0 blue:231/255.0 alpha:1];
            break;
        case 6:
            color = [UIColor colorWithRed:70/255.0 green:175/255.0 blue:147/255.0 alpha:1];
            break;
        default:
            break;
    }
    
    return color;
}



- (UIView *)createDateViewWithFrame:(CGRect)frame {
    NSString *dateString;
    
    if ((int)playerAllGamesArr.count == 0) {
        playerCurrentGameInfoArr = @[@"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0"];
        dateString = @"00-00-00";
    }
    else {
        gameDateStr = playerCurrentGameInfoArr[3];
        NSString *dateStr = [[NSString alloc] initWithFormat:@"%@-%@-%@", [gameDateStr substringWithRange:NSMakeRange(8, 4)], [gameDateStr substringWithRange:NSMakeRange(0, 3)], [gameDateStr substringWithRange:NSMakeRange(4, 2)]];
        NSDate *date = [DateString dateFromString:dateStr];
        dateString = [DateString stringFromDate:date];
    }
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    DateLabel = [CreateControl createLabelWithFrame:CGRectMake(0, 0, self.view.frame.size.width, view.frame.size.height) AndText:dateString AndTextColor:[UIColor colorWithRed:88/255.0 green:104/255.0 blue:131/255.0 alpha:1] AndBackgroundColor:[UIColor clearColor] AndTextFont:18];
    [view addSubview:DateLabel];
    
    UIImage *leftImg = [UIImage imageNamed:@"edit_arrow_left"];
    UIImage *rightImg = [UIImage imageNamed:@"edit_arrow_right"];

    UIButton *leftArrowBtn = [self createDateArrowBtnWithFrame:CGRectMake(self.view.frame.size.width / 2 - 120, view.frame.size.height / 2 - leftImg.size.height * 1.2 / 2, leftImg.size.width * 1.2, leftImg.size.height * 1.2) AndButtonImg:leftImg AndButtonTarget:@selector(touchLastDate)];
    [view addSubview:leftArrowBtn];
    
    UIButton *rightArrowBtn = [self createDateArrowBtnWithFrame:CGRectMake(self.view.frame.size.width / 2 + 110, leftArrowBtn.frame.origin.y, leftArrowBtn.frame.size.width, leftArrowBtn.frame.size.height) AndButtonImg:rightImg AndButtonTarget:@selector(touchNextDate)];
    [view addSubview:rightArrowBtn];
    
    return view;
}

- (UIButton *)createDateArrowBtnWithFrame:(CGRect)frame AndButtonImg:(UIImage *)img AndButtonTarget:(SEL)selector{
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    imgView.image = img;
    
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [button addSubview:imgView];
    
    return button;
}






- (UIView *)createAverageLabelViewWithFrame:(CGRect)frame AndNameWidth:(float)width AndName:(NSString *)name AndNameData:(NSString *)nameData {
    
    UILabel *pointDataLab = [CreateControl createLabelWithFrame:CGRectMake(0, 0, width, frame.size.height) AndText:nameData AndTextColor:[UIColor colorWithRed:126/255.0 green:138/255.0 blue:159/255.0 alpha:1] AndBackgroundColor:[UIColor clearColor] AndTextFont:18];
    
    UILabel *pointNameLab = [CreateControl createLabelWithFrame:CGRectMake(pointDataLab.frame.origin.x + pointDataLab.frame.size.width + 4, 2.2, frame.size.width - 4 - width, frame.size.height) AndText:name AndTextColor:[UIColor colorWithRed:126/255.0 green:138/255.0 blue:159/255.0 alpha:1] AndBackgroundColor:[UIColor clearColor] AndTextFont:12];
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    [view addSubview:pointDataLab];
    [view addSubview:pointNameLab];
    
    return view;
    
}


#pragma mark - other
- (void)refreshPlayerChartView {
    
    if (index >= (int)playerAllGamesArr.count) {
        index--;
    }
    
    if (index < 0) {
        index++;
    }
    
    if ((int)playerAllGamesArr.count == 0) {
        playerCurrentGameInfoArr = @[@"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0", @"0.0"];
        DateLabel.text = @"00-00-00";
                          
    }
    else {
        playerCurrentGameInfoArr = playerAllGamesArr[index];
        gameDateStr = playerCurrentGameInfoArr[3];
        
        NSString *dateStr = [[NSString alloc] initWithFormat:@"%@-%@-%@", [gameDateStr substringWithRange:NSMakeRange(8, 4)], [gameDateStr substringWithRange:NSMakeRange(0, 3)], [gameDateStr substringWithRange:NSMakeRange(4, 2)]];
        
        
        NSDate *date = [DateString dateFromString:dateStr];
        
        DateLabel.text = [DateString stringFromDate:date];

    }
    
    
    
    [self initialLineData];
    
    [lineTableView reloadData];
    
}


- (void)initialLineData {
    [lineDataDic removeAllObjects];
    
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@",playerCurrentGameInfoArr[playerCurrentGameInfoArr.count - 3]] forKey:@"Points"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[19]] forKey:@"Assists"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[18]] forKey:@"Rebounds"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[20]] forKey:@"Steals"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[21]] forKey:@"Blocks"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[22]] forKey:@"Turnovers"];
    [lineDataDic setValue:[[NSString alloc] initWithFormat:@"%@", playerCurrentGameInfoArr[6]] forKey:@"Minutes"];
}



- (NSString *)changeDecimalAccuracy:(NSString *)string {
    float floatString = [string floatValue];
    string = [[NSString alloc] initWithFormat:@"%.1f", floatString];
    
    return string;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (BOOL)prefersStatusBarHidden {
    return YES;
}




@end
